<!--
 * @Description: 领料单
 * @FilePath: \rs_wms_pc\src\views\invoice\pickingOrder\index.vue
-->
<template>
  <div class="app-container" style="height: 100%">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="100px">
      <el-form-item label="单据编号" prop="no">
        <el-input v-model="queryParams.no" placeholder="请输入单据编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="客户编号" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option v-for="dict in dict.type.invoice_order_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("search") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("reset") }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="btnGroup">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['bill:pickingOrder:add']">{{ $t("add") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['bill:pickingOrder:edit']">{{ $t("edit") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <!--<el-button type="warning" plain icon="el-icon-close" size="mini" :disabled="single" @click="cancelOrder" v-hasPermi="['invoice.pickingOrder:cancelOrder']">取消</el-button>-->
        <el-button type="warning" plain icon="el-icon-close" size="mini" :disabled="single|| selection[0].status !== 5" @click="confirmCancelOrder" v-hasPermi="['bill:pickingOrder:confirmCancel']">确认取消</el-button>
        <el-button type="primary" plain icon="el-icon-s-claim" size="mini" :disabled="single" @click="confirm" v-hasPermi="['bill.pickingOrder:confirm']">确认订单</el-button>
        <el-button type="success" plain icon="el-icon-check" size="mini" :disabled="single" @click="complete" v-hasPermi="['bill.pickingOrder:complete']">完成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['bill:pickingOrder:remove']">{{ $t("delete") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['bill:pickingOrder:import']">{{ $t("import") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['bill:pickingOrder:export']">{{ $t("export") }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="table" :height="calcTableHeight" v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" highlight-current-row @current-change="rowSelection">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" />
      <af-table-column label="单据编号" align="center" prop="no" />
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.invoice_order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <af-table-column label="工单编号" align="center" prop="workOrderNo" />
      <af-table-column label="领料人" align="center" prop="picker" />
      <el-table-column label="是否已备料" align="center" prop="whetherMp" min-width="130">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.whetherMp" />
        </template>
      </el-table-column>
      <af-table-column label="需求总数量" align="center" prop="totalQty" />
      <el-table-column label="线边仓" align="center" prop="storehouseNo" min-width="150"/>
      <af-table-column label="线边仓名称" align="center" prop="storehouseName" />
      <el-table-column label="取消原因" align="center" prop="remark" min-width="152" show-overflow-tooltip/>
      <el-table-column :label="$t('createUser')" align="center" prop="createBy" min-width="100" />
      <el-table-column :label="$t('createTime')" align="center" prop="createTime" min-width="152" />
      <el-table-column :label="$t('updateUser')" align="center" prop="updateBy" min-width="100"/>
      <el-table-column :label="$t('updateTime')" align="center" prop="updateTime" min-width="152" />
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      <!--   单据明细 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" ref="halfTable" class="half-table">
      <el-tab-pane label="领料单明细" name="detailList">
        <detailPage ref="detailPage" style="padding: unset" :orderData="orderData" />
      </el-tab-pane>
    </el-tabs>

    <!-- 添加或修改单据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body>
      <el-form ref="form" :model="form" label-width="110px">
        <el-form-item label="仓库" prop="storehouseNo" :rules="rules.storehouseNo">
          <el-select style="width: 100%" v-model="form.storehouseNo" filterable placeholder="请选择仓库">
            <el-option v-for="dict in storehouseList" :key="dict.no" :label="dict.no +' - '+dict.name" :value="dict.no" @click.native="form.storehouseName = dict.name;"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单编号" prop="workOrderNo" :rules="form.whetherMp=='Y'?rules.workOrderNo:{}">
          <el-input v-model="form.workOrderNo" placeholder="请输入工单编号" />
        </el-form-item>
        <el-form-item label="领料人" prop="picker">
          <el-input v-model="form.picker" placeholder="请输入领料人" />
        </el-form-item>
        <!-- <el-form-item label="领料人" prop="picker">
          <el-select style="width:100%;" v-model="form.picker" filterable placeholder="请选择领料人">
            <el-option v-for="(dict,index) in userList" :key="index" :label="dict.nickName" :value="dict.userName" @click.native="form.pickerName = dict.nickName"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否已备料" prop="whetherMp">
          <el-select style="width: 100%" v-model="form.whetherMp" filterable placeholder="请选择是否已备料">
            <el-option key="Y" label="是" value="Y"/>
            <el-option key="N" label="否" value="N"/>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="需求数量" prop="totalQty">
          <el-input-number v-model="form.totalQty" placeholder="请输入需求数量" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t("sure") }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          {{ $t("importTip1") }}<em>{{ $t("clickUpload") }}</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>{{ $t("importTip") }}</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">{{ $t("download") }}</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">{{ $t("sure") }}</el-button>
        <el-button @click="upload.open = false">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixin/pageSearchTable";
import { getList, getDetail, del, add, update, complete, confirm, cancel, confirmCancel } from "@/api/invoice/pickingOrder"
import { listCustomer } from "@/api/basic/customer"
import { listStorehouse } from "@/api/basic/storehouse"
import { listUser } from "@/api/system/user";
import { getToken } from "@/utils/auth"
import detailPage from "./detail"

export default {
  name: "pickingOrder",
  dicts: ["invoice_order_status", 'sys_yes_no'],
  mixins:[mixins],
  components: { detailPage },
  provide() {
    return {
      refresh:this.getList
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      nos: [],
      selection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据表格数据
      orderList: [],
      // 仓库列表
      storehouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        orderType: 1,
        orderStatus: null,
        customerNo: null,
        customerName: null,
        workOrderNo: null,
        createUser: null,
        updateUser: null,
        sort: null,
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/bill/pick/importExcel",
      },
      // 表单参数
      form: {whetherMp:'N'},
      // 表单校验
      rules: {
        storehouseNo: [{ required: true, message: "仓库不能为空", trigger: "change" }],
        workOrderNo: [{  required: true, message: "工单编号不能为空", trigger: "blur" }],
      },
      //页面下方明细的选项
      activeTab:'detailList',
      //传递给订单详情的数据
      orderData: {},
      // 用户列表
      // userList: [],
    }
  },
  created() {
    this.getListStorehouse()
    this.getList()
    // this.getUserList();
  },
  methods: {
    handleTabClick(value){
      console.log(value)
    },
    getListStorehouse() {
      listStorehouse({ isLine: "Y", pageNum: 1, pageSize: 0 }).then((response) => {
        this.storehouseList = response.rows
      })
    },
    // 获取用户列表
    // getUserList(){
    //   listUser({pageSize:0,status:0}).then(response => {
    //     this.userList = response.rows;
    //   });
    // },
    /** 查询单据列表 */
    getList() {
      this.loading = true
      getList(this.queryParams).then((response) => {
        let orderData = {...this.orderData}
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.$nextTick(()=>{
          if(orderData && orderData.id){
            let row = response.rows.find(item => item.id == orderData.id)
            this.$refs.table.setCurrentRow(row);
          }
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        no: null,
        totalQty: null,
        storehouseNo: null,
        storehouseName: null,
        remark: null,
        delFlag: null,
        createUser: null,
        updateUser: null,
        updateTime: null,
        createTime: null,
        sort: null,
        picker:null,
        pickerName:'',
        workOrderNo:null,
        whetherMp:'N'
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.rowSelection({});
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.nos = selection.map((item) => item.no)
      this.selection = selection;
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = this.$t("add")
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDetail(id).then((response) => {
        this.form = response.data
        this.open = true
        this.title = this.$t("edit")
      })
    },
    /** 订单完成 */
    complete(row) {
      this.reset()
      const ids = row.id || this.ids
      this.$modal
        .confirm(this.$t("completeTip"))
        .then(function () {
          return complete(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t("success"))
        })
        .catch(() => {})
    },
    /** 订单取消 */
    cancelOrder(row) {
      this.reset()
      const ids = row.id || this.ids
      this.$modal
        .confirm(this.$t("cancelTip"))
        .then(function () {
          return cancel(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t("success"))
        })
        .catch(() => {})
    },
    /** 订单确认取消 */
    confirmCancelOrder(row) {
      this.reset();
      const id = row.id || this.ids[0];
      this.$modal
        .confirm(this.$t("cancelTip"))
        .then(function () {
          return confirmCancel({id: id})
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t("success"))
        })
        .catch(() => {})
    },
    /** 订单确认 */
    confirm(row) {
      this.reset()
      const ids = row.id || this.ids
      this.$modal
        .confirm(this.$t("confirmTip"))
        .then(function () {
          return confirm(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t("success"))
        })
        .catch(() => {})
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            update(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("editSuc"))
              this.open = false
              this.getList()
            })
          } else {
            add(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("addSuc"))
              this.open = false
              this.resetQuery()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const nos = row.no || this.nos
      this.$modal
        .confirm(this.$t('deleteTip', { num: ids.length }))
        .then(function () {
          return del(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t("deleteSuc"))
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "bill/pick/export",
        {
          ...this.queryParams,
          ids: this.ids,
        },
        `领料单_${new Date().getTime()}.xlsx`
      )
    },
    //行选择
    rowSelection(row) {
      this.orderData = row
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "领料单导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download("bill/pick/importTemplate", {}, `领料单模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
  },
}
</script>
